<template>
  <div
    class="video-container"
    @touchstart="handleTouchStart"
    @touchmove="handleTouchMove"
    @touchend="handleTouchEnd"
  >
    <homeTop :showicon1="false" :showicon2="true" :showbar5="true"></homeTop>
    <div style="overflow: hidden">
      <div v-for="(video, index) in videoResults" :key="index" class="video-wrapper">
        <video
          :src="video.originalUrl"
          autoplay
          muted
          preload="auto"
          class="fullscreen-video"
          @click="togglePlay(index)"
          @ended="handleVideoEnded(index)"
        ></video>
        <!-- <video
        :ref="el => videoElements.value.push(el)"
        :src="video.originalUrl"
        class="fullscreen-video"
        @ended="handleVideoEnded"
      ></video> -->
        <!-- <div class="video-text-overlay">
        <p>{{ video.abstracts }}</p>
      </div> -->
        <div class="aaa_box">
          <van-barrage v-model="list" ref="barrage" :auto-play="true">
            <div class="video" style="width: 100%; height: 150px"></div>
          </van-barrage>
        </div>
        <!-- 评论 -->
        <div class="ping_box" v-if="showComments">
          <van-icon
            name="cross"
            style="float: right; color: red; font-size: 20px"
            @click="ghuanbi()"
          />
          <van-cell-group inset>
            <van-field
              v-model="message"
              rows="1"
              autosize
              label="评论"
              type="textarea"
              placeholder="请输入你的评论"
              style="float: left"
            />
          </van-cell-group>
          <van-button plain type="primary" style="float: right" @click="submitComment(video.id)"
            >发布评论</van-button
          >
        </div>
        <div class="button-container">
          <button v-if="!video.purchased" class="video-button" @click="purchaseVideo(index)">
            购买
          </button>
          <button class="video-button" @click="favoriteVideo(index)">收藏</button>
          <button class="video-button" @click="commentVideo(index)">评论</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { showNotify } from 'vant'
import { useSearchStore } from '../../stores/video'
import { getpingData } from '../../api/search'
import router from '@/router'
import homeTop from '../../components/homeTop/index.vue'

const searchStore = useSearchStore() //获取仓库的数据拿到页面
const videoResults: any = ref([]) //接收数据
const message = ref('') // 用于绑定输入框的响应式数据
const showComments = ref(false)
const defaultList = [
  { id: 100, text: '我是大耳朵图图' },
  { id: 101, text: '我才是大耳朵图图' },
  { id: 102, text: '我是美羊羊' },
  { id: 103, text: '我是喜洋洋' },
  { id: 104, text: '你们都是什么东西啊' },
  { id: 105, text: '我是小图爸爸' },
  { id: 106, text: '我是大头妈妈' }
]

const list = ref([...defaultList])
onMounted(async () => {
  // 确保传递的参数是数字类型
  await searchStore.handleSearch('1', 1, 5)
  videoResults.value = searchStore.videoResults
  console.log(videoResults.value, 'aa')
})
// 购买
const purchaseVideo = async (index: number) => {
  const video = videoResults.value[index]
  console.log('Video object:', video)
  // 确保视频对象包含 videoId 和 price 属性
  if (video && video.id && video.price) {
    try {
      // 调用仓库中的 shopdata 方法来购买视频
      await searchStore.shopdata(video.id, video.price)
      showNotify({ type: 'success', message: '视频购买成功' })
      videoResults.value[index].purchased = true // 更新购买状态为已购买
    } catch (error) {
      showNotify({ type: 'danger', message: '视频购买失败' })
    }
  }
}
//收藏
const favoriteVideo = async (index: number) => {
  const video = videoResults.value[index]
  console.log('Video object:', video)
  if (video && video.id) {
    await searchStore.handshouData(video.id)
  }
}
//评论
const commentVideo = (index: number) => {
  showComments.value = true
}
//关闭评论
const ghuanbi = () => {
  showComments.value = false
}
//发布评论
const submitComment = async (videoId: number) => {
  if (message.value.trim() !== '') {
    try {
      const { userId, sessionId } = searchStore
      const pingData = await getpingData(userId, sessionId, { videoId, content: message.value })
      console.log(pingData, '评论视频')
      if (pingData && pingData.status === 200) {
        list.value.push({ id: Math.random(), text: message.value })
        message.value = ''
        showComments.value = false
        showNotify({ type: 'success', message: '视频评论成功' })
      } else {
        showNotify({ type: 'danger', message: '视频评论失败' })
      }
    } catch (error) {
      showNotify({ type: 'danger', message: '发布评论失败' })
    }
  } else {
    showNotify({ type: 'warning', message: '评论内容不能为空' })
  }
}

const togglePlay = (index: any) => {
  const videoElement = document.querySelectorAll('video')[index]
  if (videoElement.paused) {
    videoElement.play()
    videoElement.muted = false // Unmute when manually playing
  } else {
    videoElement.pause()
  }
}
const handleVideoEnded = (index: any) => {
  const videoElement = document.querySelectorAll('video')[index]
  videoElement.currentTime = 0 // 将视频重置为开始
  videoElement.play() // 再次播放
}

const touchStartX = ref(0)
const touchEndX = ref(0)
const currentVideoIndex = ref(0) // 当前播放视频的索引
const videoElements = ref<HTMLVideoElement[]>([]) // 视频元素数组

const handleTouchStart = (event: TouchEvent) => {
  touchStartX.value = event.touches[0].clientX
}

const handleTouchMove = (event: TouchEvent) => {
  // 防止在触摸移动时触发页面滚动
  event.preventDefault()
}

const handleTouchEnd = (event: TouchEvent) => {
  touchEndX.value = event.changedTouches[0].clientX
  const swipeThreshold = 50 // 设置一个阈值，例如50px
  if (touchEndX.value - touchStartX.value > swipeThreshold) {
    // 向右滑动，播放上一个视频
    playPreviousVideo()
  } else if (touchStartX.value - touchEndX.value > swipeThreshold) {
    // 向左滑动，播放下一个视频
    playNextVideo()
  }
}

const playPreviousVideo = () => {
  // 实现播放上一个视频的逻辑
  if (currentVideoIndex.value > 0) {
    currentVideoIndex.value-- // 减少索引以播放上一个视频
    videoElements.value[currentVideoIndex.value].play() // 播放视频
  }
}

const playNextVideo = () => {
  // 实现播放下一个视频的逻辑
  if (currentVideoIndex.value < videoResults.value.length - 1) {
    currentVideoIndex.value++ // 增加索引以播放下一个视频
    videoElements.value[currentVideoIndex.value].play() // 播放视频
  }
}

//返回
const fanhuii = () => {
  router.push('/home')
}
</script>

<style scoped>
/* ... (same as before) ... */
.video-container {
  width: 100vw;
  height: 100vh;
  position: relative;
}
.topbox {
  height: 0.8rem;
  font-size: 0.7rem;
}
.video-wrapper {
  width: 100%;
  height: 100%;
  position: relative;
  object-fit: cover;
  /* display:; */
}
.fullscreen-video {
  width: 100%;
  height: 100%;
  object-fit: cover; /*视频内容覆盖整个容器，可能会被裁剪 */
}
.play-pause-button {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(160%, -190%);
  z-index: 10;
  /* background: rgba(0, 0, 0, 0.5);
  color: white; */
  border: none;
  padding: 10px 20px;
  cursor: pointer;
  font-size: 35px;
}

.button-container {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.button-container {
  position: absolute;
  top: 40%;
  left: 40%;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 20px;
  z-index: 10;
}

.video-button {
  margin: 10px 0;
  padding: 10px 20px;
  background-color: black;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
  color: white;
}

.play-pause-button van-icon {
}
.aaa_box {
  position: absolute;
  top: 1%;
  width: 100vw;
}
/* 评论 */
.ping_box {
  position: absolute;
  top: 73%;
  width: 100vw;
}
/* .play-pause-button:hover {
  background: rgba(0, 0, 0, 0.7);
} */
</style>
